/***************************************************************************
 * File name: q3.c
 * Author:  Tomer Filiba
 *          037013075
 *          sebulba@t2
 *
 * Exercise #: 3
 * Question #: 3
 * Submission Date: 01/7/07
 **************************************************************************/

/*-------------------------------------------------------------------------
  Include files:
--------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>

/*=========================================================================
  Constants and definitions:
==========================================================================*/
#define GREAT_SUCCESS		(0)
#define BIG_BAGA_BOOM		(1)
#define MAX_STRING_SIZE		(256)

/*-------------------------------------------------------------------------
  Performs Run Length Encoding (RLE) over a string read from the user
 -------------------------------------------------------------------------*/
int main(int argc, const char ** argv) 
{
	char buf[MAX_STRING_SIZE];
	char ch, last;
	int i, count;
	
	/* get line from user */
	printf("Type your text (must end with an exclamation point):\n");
	if (fgets(buf, MAX_STRING_SIZE, stdin) == NULL) {
		perror("something went wrong");
		return BIG_BAGA_BOOM;
	}
	
	/* first pass - make sure the input is valid */
	for (i = 0; i < MAX_STRING_SIZE; i++) {
		ch = buf[i];
		if (ch == '!') {
			/* string is valid up to '!'. note that fgets() appends a '\0' to the end
			 * of the string, so we will surely find a '\0' (and fail accordingly),
			 * before 'i' reaches 'MAX_STRING_SIZE' */
			break;
		}
		else if (ch == '\0' || ch == '\n') {
			printf("Error! Input must end with an exclamation point\n");
			return BIG_BAGA_BOOM;
		}
		else if ((ch < 'A' || ch > 'Z') && (ch < 'a' || ch > 'z')) {
			printf("Error! Only 'A'..'Z' and 'a'..'z' are accepted, "
				"found '%c'\n", ch);
			return BIG_BAGA_BOOM;
		}
	}
	
	/* second pass - print RLEs */
	count = 0;
	last = '\0';
	for (i = 0; (ch = buf[i]) != '!'; i++) {
		if (last == ch) {
			count++;
		}
		else {
			if (count > 0) {
				printf("%c%d", last, count);
			}
			last = ch;
			count = 1;
		}
	}
	
	/* print last part (if exists) */
	if (count > 0) {
		printf("%c%d", last, count);
	}
	printf("!\n");
	
	return GREAT_SUCCESS;
}

/**************************************************************************
                               End of file
***************************************************************************/